<template>
    <Teleport to=".header">
        <Header title="购物车"></Header>
    </Teleport>
    <div class="carts-list-box">
        <div v-if="cartList.length" class="top">
                <van-checkbox  v-model="checkedAll">全选</van-checkbox>
        </div>
        <div v-else>
            购物车为空
            <routerLink to="/cate">去购物吧^_^</routerLink>
        </div>
        <div class="cats-item"  v-for="item in cartList" :key="item.cartid">
            
            <div class="cart-content">
                <van-checkbox class="checkbox" v-model="item.flag"></van-checkbox>
                <van-card
                :price="item.originprice.toFixed(2)"
                :title='item.proname'
                :thumb="item.img1 ">
                <template #num>
                    <van-stepper 
                    disable-input
                    input-width="30px" button-size="23px"
                    theme="round" v-model="item.num" />
                </template>
                <template #footer>
                    <van-button @click="delCartHandler(item.cartid)"  size="mini">删除</van-button>

                </template>
            </van-card>
            </div>
        </div>
        <div class="bottom">
            <van-submit-bar :price="priceAll" button-text="去结算"  />

        </div>
    </div>
</template>

<script setup lang="ts">
import Header from '@/components/header.vue'
import { onMounted ,ref ,computed} from 'vue';
import { getCartsList,delCartsList } from '@/apis/addCart'


interface goods {
    [key:string]:any
}
const checked = ref<boolean>(true)
//准备一个变量，表示购物车列表
const cartList = ref<goods[]>([])

//获取购物车列表的方法
const getCartslistHandler=async()=>{
 const userId = window.localStorage.getItem('user_id')
    const res = await getCartsList(userId)
    console.log(res)
    cartList.value=res.data || []
}
//计算属性是否全选
const checkedAll =computed<boolean>({
    get(){ return cartList.value.every(item=>item.flag) } ,
    set(val){ 
        cartList.value.forEach(item=>item.flag=val)
    }
})
//计算价格
const priceAll = computed(()=>{
    return cartList.value.reduce((prev,item)=> {
        if(item.flag){
            return prev+item.num * item.originprice
        }
        return prev
    },0)*100
} )
//删除单个购物车
const delCartHandler=async(cartid:string)=>{
    const res = await delCartsList(cartid)
    getCartslistHandler()
}
onMounted(()=>{
    getCartslistHandler()
})
</script>

<style lang="scss" scoped>
.carts-list-box{
    padding: 10px;
}
.carts-list-box .cats-item{
    border-radius: 10px;
    overflow: hidden;
    background-color: #fff;
    
.checkbox{
    position: absolute;
    top: 100px;
    left: 0px;
    z-index: 100;
}
.cart-content{
    position: relative;
}
}
</style>